package com.fingard.dsp.bank.directbank.cmbc01;

import java.sql.Connection;
import java.util.*;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

@Component("CMBC01Transaction")
public class CMBC01Transaction extends CMBC01Base implements ITransaction {
    private static final String SELECTRECEIPT = "SELECT RESERVE1,RESERVE2 FROM REQSEQIDMAPPING WHERE OUTREQSEQID=? AND BANKCODE=?;";
    //采用流处理方式
    //1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用writeRetDetail()，写入返回ATS的明细

    /**
     * 明细查询：
     * d_7516_ordinaryHisTrans:普通账户明细查询
     * d_7516_OtherBankCashPoolHisTrans:他行全球现金池账户明细查询
     * d_7516_SameBankCashPoolHisTrans:同行全球现金池账户明细查询
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        if (p_req7516.actBankType.equals("11")) {//是否全球现金池账户
            Connection conn = FGBiz.getLocalDbConn();
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req7516.accountId, p_req7516.reqHeader.bankCode});
            if (map.size() == 0) {
                RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
                retAts.writeStart();//写返回ATS的统一头部信息
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("账号:" + p_req7516.actNum + "数据库没有是否民生银行标志及账号类型映射！");
                retAts.writeEnd();
                return retAts;
            }
            conn.close();
            if (map.get("RESERVE1").toString().equals("0")) {//0-他行账户 1-民生银行账户
                return d_7516_OtherBankCashPoolHisTrans(p_req7516);
            } else {
                return d_7516_SameBankCashPoolHisTrans(p_req7516);
            }
        } else if(p_req7516.actBankType.equals("14")){
            return d_7516_virtualHisTrans(p_req7516);
        }else {
        	if("detailLoad".equalsIgnoreCase(getBankConfig().getValueAsString("trnCode"+this.reqHeader.transType))){
        		return d_7516_detailLoad(p_req7516);
        	}else{
        		return d_7516_ordinaryHisTrans(p_req7516);
        	}
        }
    }

    //虚拟账户明细查询
    public RetAtsTrans d_7516_virtualHisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
//            Calendar tmpCalendarFrom = Calendar.getInstance();
//            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
//
//            Calendar tmpCalendarTo = Calendar.getInstance();
//            tmpCalendarTo.setTime(p_req7516.getDateTo());
//
//            //按自然月循环查询
//            int tmpIntDateFrom = 0;
//            int tmpIntDateTo = 0;
//            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
//                Calendar tmpClndrStepTo = Calendar.getInstance();
//                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
//                //判断是否跨月
//                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
//                    //跨月则设置为月末
//                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
//                } else {
//                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
//                }
            /**
             * 分页循环，发送报文
             */
            int tmpNowReadStart = 1;//起始页数
            int tmpNowReadNum = 0;//已查询笔数
            Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
            while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                //赋值通用参数
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                CMBC01Header bankHeader = new CMBC01Header();
                bankHeader.trnCode = "B2EVirtualAcctTransDetailQry";
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("xDataBody");
                String trnId=getQryTransID();
                xmlWriter.writeElementString("trnId", trnId);
                xmlWriter.writeElementString("cltcookie", "");
                xmlWriter.writeElementString("insId", trnId);
                xmlWriter.writeElementString("AcNo", p_req7516.higherLevelAct);
                xmlWriter.writeElementString("VirtualAcNo", p_req7516.actNum);
                xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(p_req7516.getDateFrom()));//起始日期
                xmlWriter.writeElementString("EndDate", Format.Date10Format.format(p_req7516.getDateTo()));//结束日期
                xmlWriter.writeElementString("currentIndex", tmpNowReadStart + "");//起始位置
                xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));//默认每页显示数据
                xmlWriter.writeEndDocument();
                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                        String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                        if (tmpRetMessage.equals("无记录")) {
                            break;
                        }
                        if (tmpRetCode.equals("0")) {
                            //符合条件的条数，总明细数
                            String totalCount = tmpBkReader.getFirstText("/CMBC/xDataBody/recordNumber");
                            if (tmpTotalNum.containsKey("totalCount")) {
                                if (!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "相同条件前后查出来的总数不一致";
                                    break;
                                }
                            } else {
                                if ("0".equals(totalCount)) {
                                    tmpRespCode = "0";
                                    tmpRespInfo = "该时间段的总明细条数为0";
                                    break;
                                }
                                tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));//记录总条数
                            }
                            int readCount = 0;
                            while (tmpBkReader.read("/CMBC/xDataBody/List/Map")) {
                                XElement readXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                tmpRetDetail.cur=p_req7516.actCur;
                                tmpRetDetail.recAccNum = readXElement.getSingleText("OppAcNo");//对方账号
                                tmpRetDetail.recAccName = readXElement.getSingleText("OppAcName");//对方户名
                                tmpRetDetail.tranDate = readXElement.getSingleText("TransDate");//交易日期
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate+" "+readXElement.getSingleText("TransTime");//交易时间
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日期
                                tmpRetDetail.accBal = readXElement.getSingleText("SelfBalance");//余额
                                String loanAmount=readXElement.getSingleText("LoanAmount");//借方金额
                                String selfBalance=readXElement.getSingleText("SelfBalance");//贷方金额
                                if(StringHelper.hasAnyChar(loanAmount) && Double.parseDouble(loanAmount)>0){
                                    tmpRetDetail.cdFlag = "1";//1：借（支出）2：贷（收入）
                                    tmpRetDetail.tranAmt = loanAmount;//交易金额
                                }else if(StringHelper.hasAnyChar(selfBalance) && Double.parseDouble(selfBalance)>0){
                                    tmpRetDetail.cdFlag = "2";//1：借（支出）2：贷（收入）
                                    tmpRetDetail.tranAmt = selfBalance;//交易金额
                                }
                                tmpRetDetail.comment = readXElement.getSingleText("Remark");//备注
                                retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                readCount++;
                            }
                            tmpNowReadNum += readCount;//已查询条数
                            if (Integer.parseInt(totalCount) > tmpNowReadNum) {
                                //总条数大于已查询条数，说明查询了默认条数的明细
                                if (readCount != Integer.valueOf(getBankConfig().getValueAsString("pageSize"))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "总条数大于已查询条数,统计明细有误";
                                    break;
                                }
                            }
                            if (Integer.parseInt(totalCount) < tmpNowReadNum) {
                                //总条数小于已查询条数,说明数据异常
                                tmpRespCode = "-1";
                                tmpRespInfo = "总条数小于已查询条数,统计明细有误";
                                break;
                            }
                            tmpNowReadStart++;//查询起始页加1
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMessage;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    break;
                }
            }
//                tmpCalendarFrom = tmpClndrStepTo;
//                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
//                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
//                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
//            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }
        retAts.writeEnd();
        return retAts;
    }


    //全球现金池 他行 账户明细查询
    public RetAtsTrans d_7516_OtherBankCashPoolHisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
//            Calendar tmpCalendarFrom = Calendar.getInstance();
//            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
//
//            Calendar tmpCalendarTo = Calendar.getInstance();
//            tmpCalendarTo.setTime(p_req7516.getDateTo());
//
//            //按自然月循环查询
//            int tmpIntDateFrom = 0;
//            int tmpIntDateTo = 0;
//            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
//                Calendar tmpClndrStepTo = Calendar.getInstance();
//                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
//                //判断是否跨月
//                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
//                    //跨月则设置为月末
//                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
//                } else {
//                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
//                }
            /**
             * 分页循环，发送报文
             */
            int tmpNowReadStart = 1;//起始页数
            int tmpNowReadNum = 0;//已查询笔数
            Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
            while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                //赋值通用参数
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                CMBC01Header bankHeader = new CMBC01Header();
                bankHeader.trnCode = "CBOtherBankTransDetailQry";
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("xDataBody");
                xmlWriter.writeElementString("trnId", Format.DateTime17Format.format(new Date()));
                xmlWriter.writeElementString("accountId", p_req7516.accountId);
                xmlWriter.writeElementString("account", p_req7516.actNum);
//                    xmlWriter.writeElementString("qryStartDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));
//                    xmlWriter.writeElementString("qryEndDate", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                String qryStartDate = p_req7516.dateFrom.substring(0, 4) + "-" + p_req7516.dateFrom.substring(4, 6) + "-" + p_req7516.dateFrom.substring(6, 8);
                String qryEndDate = p_req7516.dateTo.substring(0, 4) + "-" + p_req7516.dateTo.substring(4, 6) + "-" + p_req7516.dateTo.substring(6, 8);
                xmlWriter.writeElementString("qryStartDate", qryStartDate);
                xmlWriter.writeElementString("qryEndDate", qryEndDate);
                xmlWriter.writeElementString("pageNo", tmpNowReadStart + "");//翻页起始页
                xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));//默认每页显示数据
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                        String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                        if (tmpRetMessage.equals("无记录")) {
                            break;
                        }
                        if (tmpRetCode.equals("0")) {
                            //符合条件的条数，总明细数
                            String totalCount = tmpBkReader.getFirstText("/CMBC/xDataBody/allNum");
                            if (tmpTotalNum.containsKey("totalCount")) {
                                if (!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "相同条件前后查出来的总数不一致";
                                    break;
                                }
                            } else {
                                if ("0".equals(totalCount)) {
                                    tmpRespCode = "0";
                                    tmpRespInfo = "该时间段的总明细条数为0";
                                    break;
                                }
                                tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));//记录总条数
                            }
                            int readCount = 0;
                            while (tmpBkReader.read("/CMBC/xDataBody/List/Map")) {
                                XElement readXElement = tmpBkReader.readedXElement;
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                tmpRetDetail.recAccNum = readXElement.getSingleText("oppAccNo");//对方账号
                                tmpRetDetail.valueDate = readXElement.getSingleText("valueDate");//起息日期
                                tmpRetDetail.cdFlag = readXElement.getSingleText("dcFlag").equals("0") ? "1" : "2";//1：借（支出）2：贷（收入）
                                tmpRetDetail.tranAmt = readXElement.getSingleText("amount");//交易金额
                                tmpRetDetail.comment = readXElement.getSingleText("supContent");//备注
                                tmpRetDetail.cur = convertCurToATS(readXElement.getSingleText("currencyCode"));//币种代码
                                tmpRetDetail.curName = readXElement.getSingleText("currencyName");//币种名称
                                tmpRetDetail.curName = readXElement.getSingleText("referenceNo");//开户行业务编号
                                tmpRetDetail.curName = readXElement.getSingleText("accBizNo");//账户行业务编号
                                retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                readCount++;
                            }
                            tmpNowReadNum += readCount;//已查询条数
                            if (Integer.parseInt(totalCount) > tmpNowReadNum) {
                                //总条数大于已查询条数，说明查询了默认条数的明细
                                if (readCount != Integer.valueOf(getBankConfig().getValueAsString("pageSize"))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "总条数大于已查询条数,统计明细有误";
                                    break;
                                }
                            }
                            if (Integer.parseInt(totalCount) < tmpNowReadNum) {
                                //总条数小于已查询条数,说明数据异常
                                tmpRespCode = "-1";
                                tmpRespInfo = "总条数小于已查询条数,统计明细有误";
                                break;
                            }
                            tmpNowReadStart++;//查询起始页加1
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMessage;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    break;
                }
            }
//                tmpCalendarFrom = tmpClndrStepTo;
//                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
//                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
//                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
//            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }
        retAts.writeEnd();
        return retAts;
    }

    //全球现金池 同行 账户明细查询
    public RetAtsTrans d_7516_SameBankCashPoolHisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
//            Calendar tmpCalendarFrom = Calendar.getInstance();
//            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
//
//            Calendar tmpCalendarTo = Calendar.getInstance();
//            tmpCalendarTo.setTime(p_req7516.getDateTo());
//
//            //按自然月循环查询
//            int tmpIntDateFrom = 0;
//            int tmpIntDateTo = 0;
//            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
//                Calendar tmpClndrStepTo = Calendar.getInstance();
//                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
//                //判断是否跨月
//                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
//                    //跨月则设置为月末
//                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
//                } else {
//                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
//                }
            /**
             * 分页循环，发送报文
             */
            int tmpNowReadStart = 1;//起始页数
            int tmpNowReadNum = 0;//已查询笔数
            Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
            while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                //赋值通用参数
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                CMBC01Header bankHeader = new CMBC01Header();
                bankHeader.trnCode = "CBDetailLoad";
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("xDataBody");
                xmlWriter.writeElementString("trnId", Format.DateTime17Format.format(new Date()));
                xmlWriter.writeElementString("accountId", p_req7516.accountId);
                xmlWriter.writeElementString("acntNo", p_req7516.actNum);
//                    xmlWriter.writeElementString("dateFrom", Format.Date10Format.format(tmpCalendarFrom.getTime()));
//                    xmlWriter.writeElementString("dateTo", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                String qryStartDate = p_req7516.dateFrom.substring(0, 4) + "-" + p_req7516.dateFrom.substring(4, 6) + "-" + p_req7516.dateFrom.substring(6, 8);
                String qryEndDate = p_req7516.dateTo.substring(0, 4) + "-" + p_req7516.dateTo.substring(4, 6) + "-" + p_req7516.dateTo.substring(6, 8);
                xmlWriter.writeElementString("dateFrom", qryStartDate);
                xmlWriter.writeElementString("dateTo", qryEndDate);
                xmlWriter.writeElementString("startNo", tmpNowReadStart + "");//翻页起始页
                xmlWriter.writeElementString("queryRows", getBankConfig().getValueAsString("pageSize"));//默认每页显示数据
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                        String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                        if (tmpRetMessage.equals("无记录")) {
                            break;
                        }
                        if (tmpRetCode.equals("0")) {
                            //符合条件的条数，总明细数
                            String totalCount = tmpBkReader.getFirstText("/CMBC/xDataBody/totalNum");
                            if (tmpTotalNum.containsKey("totalCount")) {
                                if (!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "相同条件前后查出来的总数不一致";
                                    break;
                                }
                            } else {
                                if ("0".equals(totalCount)) {
                                    tmpRespCode = "0";
                                    tmpRespInfo = "查询页:" + tmpNowReadStart + ",明细条数为0";
                                    break;
                                }
                                tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));//记录总条数
                            }
                            int readCount = 0;
                            String tmpDataMFS = tmpBkReader.getFirstText("/CMBC/xDataBody/dataStream");
                            if (tmpDataMFS != null) {
                                //包含头部
                                //0交易日期|1主机交易流水号|2借方发生额|3贷方发生额|4帐户余额|5凭证种类|6企业自制凭证号|7摘要|
                                //8交易地点|9对方帐号|10对方帐号名称|11对方开户行|12交易时间戳|
                                StringBuilder tmpSbLog = new StringBuilder();
                                ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", 13, -1, tmpSbLog);
                                if (tmpSbLog.length() == 0) {
                                    for (int i = 1; i < tmpArrayList.size(); i++) {
                                        String[] tmpEachArr = tmpArrayList.get(i);
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                        tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                        tmpRetDetail.recAccNum = tmpEachArr[9].trim();//对方账号
                                        tmpRetDetail.recAccName = tmpEachArr[10].trim();//对方户名
                                        String tmpRecBank = StringHelper.convertToDBC(tmpEachArr[11]).trim();
                                        tmpRetDetail.recAccBank = tmpRecBank;//对方开户银行
                                        //交易日期
                                        tmpRetDetail.tranDate = tmpEachArr[0].substring(4, 8) + "-" + tmpEachArr[0].substring(8, 10) + "-" + tmpEachArr[0].substring(10, 12);
                                        //交易时间
                                        tmpRetDetail.tranTime = tmpEachArr[12].substring(0, 4) + "-" + tmpEachArr[12].substring(4, 6) + "-" + tmpEachArr[12].substring(6, 8) + " " + tmpEachArr[12].substring(8, 10) + ":" + tmpEachArr[12].substring(10, 12) + ":" + tmpEachArr[12].substring(12, 14);
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日期
                                        String payAmount = tmpEachArr[2];//借方发生额
                                        String recAmount = tmpEachArr[3];//贷方发生额
                                        if (Float.parseFloat(payAmount) != 0) {
                                            tmpRetDetail.cdFlag = "1";//1：借（支出）
                                            tmpRetDetail.tranAmt = payAmount;//交易金额
                                        } else {
                                            tmpRetDetail.cdFlag = "2";//2：贷（收入）
                                            tmpRetDetail.tranAmt = recAmount;//交易金额
                                        }
                                        tmpRetDetail.accBal = tmpEachArr[4];//账号余额
                                        tmpRetDetail.postTimestamp = tmpEachArr[12];//时间戳
                                        tmpRetDetail.usage = tmpEachArr[7];//用途(摘要)
                                        tmpRetDetail.originator = tmpEachArr[1];//银行返回流水号
                                        tmpRetDetail.billNum = tmpEachArr[6];//凭证号
                                        nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                        readCount++;
                                        retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = tmpSbLog.toString();
                                    break;
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = "查询页:" + tmpNowReadStart + "，查询明细条数不为0，但是数据域为空";
                                break;
                            }
                            tmpNowReadNum += readCount;//已查询条数
                            if (Integer.parseInt(totalCount) > tmpNowReadNum) {
                                //总条数大于已查询条数，说明查询了默认条数的明细
                                if (readCount != Integer.valueOf(getBankConfig().getValueAsString("pageSize"))) {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "总条数大于已查询条数,统计明细有误";
                                    break;
                                }
                            }
                            if (Integer.parseInt(totalCount) < tmpNowReadNum) {
                                //总条数小于已查询条数,说明数据异常
                                tmpRespCode = "-1";
                                tmpRespInfo = "总条数小于已查询条数,统计明细有误";
                                break;
                            }
                            tmpNowReadStart += readCount;//查询起始记录数偏移
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMessage;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpRetBkStr[1];
                    break;
                }
            }
//                tmpCalendarFrom = tmpClndrStepTo;
//                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
//                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
//                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
//            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }
        retAts.writeEnd();
        return retAts;
    }


    //普通账户明细查询
    public RetAtsTrans d_7516_ordinaryHisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            //bnkTrncod = "b2e0035";//交易代码
            //Date tmpDateFrom = p_req7516.getDateFrom();
            //Date tmpDateTo = p_req7516.getDateTo();

            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            if ("true".equals(getBankConfig().getValueAsString("queryTransIsFlag"))) {
                int qryCount = 0;
                int tmpAllNum = -1;//总条数
                int tmpReadedNum = 0;//已读取数
                int tmpEachReqLen = 50;//每次请求条数
                int tmpStartNO = 1;//请求起始行号
                int tmpEndNO = 1;//请求结束行号
                while (tmpRespCode.length() == 0) {//分页查询
                    qryCount++;
                    tmpEndNO = tmpStartNO + tmpEachReqLen - 1;
                    if (tmpAllNum > 0 && tmpEndNO > (tmpAllNum + 1)) {
                        tmpEndNO = tmpAllNum + 1;
                    }
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    CMBC01Header bankHeader = new CMBC01Header();
                    bankHeader.trnCode = "qryDtl";
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("xDataBody");
                    xmlWriter.writeElementString("trnId", p_req7516.reqHeader.transSeqID + qryCount);
                    xmlWriter.writeElementString("cltcookie", String.valueOf(tmpStartNO));
                    xmlWriter.writeElementString("acntNo", p_req7516.actNum);
                    xmlWriter.writeElementString("dateFrom", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("dateTo", Format.Date10Format.format(tmpCalendarTo.getTime()));
                    xmlWriter.writeElementString("startNo", String.valueOf(tmpStartNO));
                    xmlWriter.writeElementString("endNo", String.valueOf(tmpEndNO));
                    xmlWriter.writeElementString("typeCode", "0");
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), true);
                    XmlTextReader tmpBkReader;
                    int tmpPageRdNum = 0;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                            String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                            if (tmpRetCode.equals("0")) {
                                //当前页记录数
                                tmpPageRdNum = Integer.parseInt(tmpBkReader.getFirstText("/CMBC/xDataBody/totalNum"));
                                if (tmpPageRdNum > 0) {
                                    tmpReadedNum = tmpReadedNum + tmpPageRdNum;
                                } else {
                                    break;
                                }
                                //总记录数
                                int tmpTtlRdNumCmp = Integer.parseInt(tmpBkReader.getFirstText("/CMBC/xDataBody/allNum"));
                                if (tmpAllNum == -1) {
                                    tmpAllNum = tmpTtlRdNumCmp;
                                }
                                if (tmpTtlRdNumCmp != tmpAllNum) {
                                    throw new Exception("银行返回的总笔数" + tmpTtlRdNumCmp + "与查询第一页时返回的总笔数" + tmpAllNum + "不相等");
                                }
                                int tmpRdCountCmp = 0;
                                while (tmpBkReader.read("/CMBC/xDataBody/dtlList/dtlInfo")) {
                                    tmpRdCountCmp++;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

                                    tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("acntNo");
                                    tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("opAcntNo");
                                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("opAcntName");
                                    tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("opBankName");
                                    String typeCD = tmpBkReader.readedXElement.getSingleText("type");
                                    tmpRetDetail.cdFlag = typeCD;
                                    String amount = tmpBkReader.readedXElement.getSingleText("amount");
                                    tmpRetDetail.tranAmt = amount.replace("-", "");
                                    if (typeCD.equals("1") && amount.indexOf("-") >= 0) {
                                        tmpRetDetail.cdFlag = "2";
                                    } else if (typeCD.equals("2") && amount.indexOf("-") >= 0) {
                                        tmpRetDetail.cdFlag = "1";
                                    }
                                    tmpRetDetail.tranDate = tmpBkReader.readedXElement.getSingleText("actDate");
                                    tmpRetDetail.valueDate = tmpBkReader.readedXElement.getSingleText("intrDate");
                                    tmpRetDetail.postTimestamp = tmpBkReader.readedXElement.getSingleText("timestamp");
                                    if (tmpRetDetail.postTimestamp != null && tmpRetDetail.postTimestamp.length() >= 6) {
                                        String timeStr = tmpRetDetail.postTimestamp.substring(0, 2) + ":" + tmpRetDetail.postTimestamp.substring(2, 4) + ":" + tmpRetDetail.postTimestamp.substring(4, 6);
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + timeStr;
                                    } else {
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate;
                                    }
                                    tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance");
                                    tmpRetDetail.billNum = tmpBkReader.readedXElement.getSingleText("chequeNum");
                                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("explain");
                                    tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("recseq");
                                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("svrId");
                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);

                                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                                if (tmpRdCountCmp != tmpPageRdNum) {
                                    throw new Exception("银行返回的当前页笔数" + tmpPageRdNum + "与实际读取的笔数" + tmpRdCountCmp + "不相等");
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpRetMessage;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                    if (tmpEndNO >= (tmpAllNum + 1)) {
                        break;
                    }
                    tmpStartNO = tmpStartNO + tmpEachReqLen - 1;//重置StartNO
                    if (tmpPageRdNum == 0) {
                        break;
                    }
                }//分页查询
                if (tmpReadedNum > 0 && tmpReadedNum != tmpAllNum) {
                    tmpRespCode = "-1";
                    tmpRespInfo = "实际取到明细条数" + tmpReadedNum + "与预期" + tmpAllNum + "不符";
                }
            } else {
                int qryCount = 0;
                int tmpIntDateFrom = 0;
                int tmpIntDateTo = 0;
                //按自然月循环查询
                while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                    Calendar tmpClndrStepTo = Calendar.getInstance();
                    tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                    //判断是否跨月
                    if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                        //跨月则设置为月末
                        tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                    } else {
                        tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                    }

                    int tmpAllNum = -1;//总条数
                    int tmpReadedNum = 0;//已读取数
                    int tmpEachReqLen = 50;//每次请求条数
                    int tmpStartNO = 1;//请求起始行号
                    int tmpEndNO = 1;//请求结束行号

                    while (tmpRespCode.length() == 0) {//分页查询
                        qryCount++;
                        tmpEndNO = tmpStartNO + tmpEachReqLen - 1;
                        if (tmpAllNum > 0 && tmpEndNO > (tmpAllNum + 1)) {
                            tmpEndNO = tmpAllNum + 1;
                        }
                        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                        //写入通用的头部节点
                        CMBC01Header bankHeader = new CMBC01Header();
                        bankHeader.trnCode = "qryDtl";
                        writeCommonHeader(xmlWriter, bankHeader);
                        xmlWriter.writeStartElement("xDataBody");
                        xmlWriter.writeElementString("trnId", p_req7516.reqHeader.transSeqID + qryCount);
                        xmlWriter.writeElementString("cltcookie", String.valueOf(tmpStartNO));
                        xmlWriter.writeElementString("acntNo", p_req7516.actNum);
                        xmlWriter.writeElementString("dateFrom", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                        xmlWriter.writeElementString("dateTo", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                        xmlWriter.writeElementString("startNo", String.valueOf(tmpStartNO));
                        xmlWriter.writeElementString("endNo", String.valueOf(tmpEndNO));
                        xmlWriter.writeElementString("typeCode", "0");
                        xmlWriter.writeEndDocument();

                        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), true, p_req7516.reqHeader.transType, p_req7516.reqHeader.commandCode);
                        XmlTextReader tmpBkReader;
                        int tmpPageRdNum = 0;
                        if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                                String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                                if (tmpRetCode.equals("0")) {
                                    //当前页记录数
                                    tmpPageRdNum = Integer.parseInt(tmpBkReader.getFirstText("/CMBC/xDataBody/totalNum"));
                                    if (tmpPageRdNum > 0) {
                                        tmpReadedNum = tmpReadedNum + tmpPageRdNum;
                                    } else {
                                        break;
                                    }
                                    //总记录数
                                    int tmpTtlRdNumCmp = Integer.parseInt(tmpBkReader.getFirstText("/CMBC/xDataBody/allNum"));
                                    if (tmpAllNum == -1) {
                                        tmpAllNum = tmpTtlRdNumCmp;
                                    }
                                    if (tmpTtlRdNumCmp != tmpAllNum) {
                                        throw new Exception("银行返回的总笔数" + tmpTtlRdNumCmp + "与查询第一页时返回的总笔数" + tmpAllNum + "不相等");
                                    }
                                    int tmpRdCountCmp = 0;
                                    while (tmpBkReader.read("/CMBC/xDataBody/dtlList/dtlInfo")) {
                                        tmpRdCountCmp++;
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

                                        tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("acntNo");
                                        tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("opAcntNo");
                                        tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("opAcntName");
                                        tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("opBankName");
                                        String typeCD = tmpBkReader.readedXElement.getSingleText("type");
                                        tmpRetDetail.cdFlag = typeCD;
                                        String amount = tmpBkReader.readedXElement.getSingleText("amount");
                                        tmpRetDetail.tranAmt = amount.replace("-", "");
                                        if (typeCD.equals("1") && amount.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "2";
                                        } else if (typeCD.equals("2") && amount.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "1";
                                        }
                                        tmpRetDetail.tranDate = tmpBkReader.readedXElement.getSingleText("actDate");
                                        tmpRetDetail.valueDate = tmpBkReader.readedXElement.getSingleText("intrDate");
                                        tmpRetDetail.postTimestamp = tmpBkReader.readedXElement.getSingleText("timestamp");
                                        if (tmpRetDetail.postTimestamp != null && tmpRetDetail.postTimestamp.length() >= 6) {
                                            String timeStr = tmpRetDetail.postTimestamp.substring(0, 2) + ":" + tmpRetDetail.postTimestamp.substring(2, 4) + ":" + tmpRetDetail.postTimestamp.substring(4, 6);
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + timeStr;
                                        } else {
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate;
                                        }
                                        tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance");
                                        tmpRetDetail.billNum = tmpBkReader.readedXElement.getSingleText("chequeNum");
                                        String explain = tmpBkReader.readedXElement.getSingleText("explain");

                                        tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("recseq");
                                        tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("svrId");
//                                        tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                        nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());

                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                    if (tmpRdCountCmp != tmpPageRdNum) {
                                        throw new Exception("银行返回的当前页笔数" + tmpPageRdNum + "与实际读取的笔数" + tmpRdCountCmp + "不相等");
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = tmpRetMessage;
                                    break;
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpSbMsg.toString();
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpStrRet[1];
                            break;
                        }
                        if (tmpEndNO >= (tmpAllNum + 1)) {
                            break;
                        }
                        tmpStartNO = tmpStartNO + tmpEachReqLen - 1;//重置StartNO
                        if (tmpPageRdNum == 0) {
                            break;
                        }
                    }//分页查询

                    if (tmpReadedNum > 0 && tmpReadedNum != tmpAllNum) {
                        tmpRespCode = "-1";
                        tmpRespInfo = "实际取到明细条数" + tmpReadedNum + "与预期" + tmpAllNum + "不符";
                        break;
                    }

                    tmpCalendarFrom = tmpClndrStepTo;
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            this.WriteBankLogLn(e);
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    /**银企直连明细下载(detailLoad) ，通过配置项<trnCode7516>切换查询接口*/
    private RetAtsTrans d_7516_detailLoad(Req7516HisTrans p_req7516) throws Exception{
    	//历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
        	//按日遍历进行下载
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());
			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());
			int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
			int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			//每页笔数
			int queryRows = this.getBankConfig().getValueAsInt("detailLoadPageSize", 3000);
			while (tmpIntFrom <= tmpIntTo) {
				Date oneDay = tmpCalendarFrom.getTime();
				//下载明细时起始笔数必须大于0且不能超过最大查询记录数，最大查询记录不能超过10000且不能小于0
				int startNo = 1;
				int totalNum = 0;
				int tmpRdCountCmp = 0;//实际查回笔数，校验用
				do{
					XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
		            //写入通用的头部节点
		            CMBC01Header bankHeader = new CMBC01Header();
		            bankHeader.trnCode = "detailLoad";
		            writeCommonHeader(xmlWriter, bankHeader);
		            xmlWriter.writeStartElement("xDataBody");
		            String trnId = getTrnId();
	                xmlWriter.writeElementString("trnId", trnId);
		            xmlWriter.writeElementString("acntNo", p_req7516.actNum);
		            xmlWriter.writeElementString("dateFrom", Format.Date10Format.format(oneDay));
		            xmlWriter.writeElementString("dateTo", Format.Date10Format.format(oneDay));
		            xmlWriter.writeElementString("startNo", String.valueOf(startNo));
		            xmlWriter.writeElementString("queryRows", String.valueOf(queryRows));
		            xmlWriter.writeElementString("typeCode", "0");
		            xmlWriter.writeEndDocument();
		            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), true);
		            if (tmpStrRet[0].length() == 0) {
		            	StringBuilder tmpSbMsg = new StringBuilder();
		                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
		                if (tmpBkReader != null) {
		                	String tmpRetCode = tmpBkReader.getFirstTextNotNull("/CMBC/responseHeader/status/code").trim();
		                    String tmpRetMessage = tmpBkReader.getFirstTextNotNull("/CMBC/responseHeader/status/message").trim();
		                    if ("无记录".equals(tmpRetMessage)) {
		                        break;
		                    }
		                    if (tmpRetCode.equals("0")) {
		                    	if(totalNum == 0){
		                    		String bkTotalNum = tmpBkReader.getFirstTextNotNull("/CMBC/xDataBody/totalNum").trim();
		                    		if(StringHelper.hasAnyChar(bkTotalNum.trim())){
		                    			totalNum = Integer.parseInt(bkTotalNum.trim());
		                    		}
		                    	}
		                    	if(totalNum <= 0){
		                    		break;
		                    	}
		                    	String dataStream = tmpBkReader.getFirstTextNotNull("/CMBC/xDataBody/dataStream").trim();
		                    	/*交易日期|主机交易流水号|借方发生额|贷方发生额|帐户余额|凭证种类|凭证号|摘要|交易地点|对方帐号|对方帐号名称|对方开户行|交易时间戳|
		                    	 * 0x0A20120814|010093040067|0.00|10000000.00|10036386.70|||大额汇兑来帐|中国民生银行总行营业部|110801040000851|北京普德金属集团有限公司|中国农业银行股份有限公司北京市分行集中作业中心(不对外营业）|20120814102011.583|0x0A20120814|000120600242|10000000.00|0.00|36386.70|新版清分机支票|3901000872494|转存保证金|中国民生银行总行营业部||||20120814102534.624|*/
		                    	//char spChar = 0x0A;
		                    	String spChar = "0x0A";
		                    	ArrayList<HashMap<String,String>> dataList = MFSHelper.pickupFirstLineIsColumn(dataStream, spChar, "\\|");
		                    	for(int i=0;i<dataList.size();i++){
		                    		tmpRdCountCmp++;
		                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
		                            tmpRetDetail.actNum = p_req7516.actNum;
		                            HashMap<String,String> eachData = dataList.get(i);
		                            if(eachData.containsKey("交易日期")){
		                            	tmpRetDetail.tranDate = DateHelper.convertD8toD10(eachData.get("交易日期").trim());
		                            	tmpRetDetail.valueDate = tmpRetDetail.tranDate;
		                            }else{
		                            	throw new Exception("不存在列“交易日期”");
		                            }
		                            if(eachData.containsKey("对方帐号")){
		                            	tmpRetDetail.recAccNum = eachData.get("对方帐号").trim();
		                            }
		                            if(eachData.containsKey("对方帐号名称")){
		                            	tmpRetDetail.recAccName = eachData.get("对方帐号名称").trim();
		                            }
		                            if(eachData.containsKey("对方开户行")){
		                            	tmpRetDetail.recAccBank = eachData.get("对方开户行").trim();
		                            }
		                            if(eachData.containsKey("主机交易流水号")){
		                            	tmpRetDetail.receiptNo = eachData.get("主机交易流水号").trim();
		                            	tmpRetDetail.bnkSeqNo = tmpRetDetail.receiptNo;
		                            }
		                            if(eachData.containsKey("帐户余额")){
		                            	tmpRetDetail.accBal = eachData.get("帐户余额").trim();
		                            }
		                            if(eachData.containsKey("凭证号")){
		                            	tmpRetDetail.billNum = eachData.get("凭证号").trim();
		                            }
		                            if(eachData.containsKey("凭证种类")){
		                            	tmpRetDetail.billType = eachData.get("凭证种类").trim();
		                            }
		                            if(eachData.containsKey("摘要")){
		                            	tmpRetDetail.usage = eachData.get("摘要").trim();
		                            }
		                            if(eachData.containsKey("交易时间戳")){
		                            	tmpRetDetail.postTimestamp = eachData.get("交易时间戳").trim();
		                            }
		                            
		                            String amount1 = "";
		                            if(eachData.containsKey("借方发生额")){
		                            	amount1 = eachData.get("借方发生额").trim();
		                            	if("0.00".equals(amount1) || "0".equals(amount1)){
		                            		amount1 = "";
		                            	}
		                            }
		                            String amount2 = "";
		                            if(eachData.containsKey("贷方发生额")){
		                            	amount2 = eachData.get("贷方发生额").trim();
		                            	if("0.00".equals(amount2) || "0".equals(amount2)){
		                            		amount2 = "";
		                            	}
		                            }
		                            String typeCD = "";
		                            String amount = "";
		                            if(amount1.length() > 0 && amount2.length() == 0){
		                            	typeCD = "1";
		                            	amount = amount1;
		                            }else if(amount1.length() == 0 && amount2.length() > 0){
		                            	typeCD = "2";
		                            	amount = amount2;
		                            }else{
		                            	throw new Exception("借方发生额"+amount1+"和贷方发生额"+amount2+"不能同时有值或都无值");
		                            }
		                            tmpRetDetail.cdFlag = typeCD;
		                            tmpRetDetail.tranAmt = amount.replace("-", "");
		                            if (typeCD.equals("1") && amount.indexOf("-") >= 0) {
		                                tmpRetDetail.cdFlag = "2";
		                            } else if (typeCD.equals("2") && amount.indexOf("-") >= 0) {
		                                tmpRetDetail.cdFlag = "1";
		                            }
		                            
		                            if(eachData.containsKey("交易地点")){
		                            	tmpRetDetail.comment = eachData.get("交易地点").trim();
		                            }
		                            
		                            //20120814102534.624
		                            String pts = tmpRetDetail.postTimestamp;
		                            if (pts != null && pts.length() >= 14) {
		                                tmpRetDetail.tranTime = pts.substring(0,4)+"-"+pts.substring(4,6)+"-"+pts.substring(6,8)+" "+pts.substring(8,10)+ ":" +pts.substring(10,12)+ ":" +pts.substring(12,14);
		                            } else {
		                                tmpRetDetail.tranTime = tmpRetDetail.tranDate;
		                            }
		                            tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);

		                            //nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());

		                            retAts.writeRetDetail(tmpRetDetail);
		                    	}
		                    	
		                    	if(tmpRdCountCmp<totalNum){
		                    		int expectNum = startNo+queryRows-1;
		                    		if(expectNum != tmpRdCountCmp){
		                    			throw new Exception("总笔数"+totalNum+"，当前已查回记录数："+ tmpRdCountCmp + "，每页"+queryRows+ "，当前startNo（不含本次）为" + startNo + "，不符合预期");
		                    		}
		                    	}
		                    }else{
		                    	break;
		                    }
		                }else {
		                    tmpRespCode = "-1";
		                    tmpRespInfo = tmpSbMsg.toString();
		                    break;
		                }
		            } else {
		                tmpRespCode = "-1";
		                tmpRespInfo = tmpStrRet[1];
		                break;
		            }
		            
		            startNo = tmpRdCountCmp+1;
				}while(startNo<=totalNum && tmpRdCountCmp<totalNum);
				
				if("-1".equals(tmpRespCode)){
	            	break;
	            }
				if(tmpRdCountCmp!= totalNum){
					tmpRespCode = "-1";
					tmpRespInfo = "实际查回的记录数"+tmpRdCountCmp+"与预期"+totalNum+"不符";
					break;
				}
				//继续查后面的日期
				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
			}
        	
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            this.WriteBankLogLn(e);
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }
    
    @Override
    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用b2e0035
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        tmpReq7516.actBankType = p_req7515.actBankType;
        tmpReq7516.accountId = p_req7515.accountId;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
